<template>
    <div class="goods-management-container">
        <div class="header-card">
            <h2>商品管理</h2>
            <p>管理平台商品信息</p>
        </div>

        <el-card class="table-card" shadow="never">
            <div class="toolbar">
                <el-button type="primary" @click="addGoods" icon="el-icon-plus">新增商品</el-button>
                <div class="search-area">
                    <el-select v-model="filterShopId" placeholder="请选择商家" clearable
                        style="width: 150px; margin-left: 10px;" @change="fetchData">
                        <el-option label="全部商家" :value="null"></el-option>
                        <el-option v-for="shop in shopOptions" :key="shop.id" :label="shop.shop_name"
                            :value="shop.id" />
                    </el-select>

                    <el-select v-model="filterCategoryId" placeholder="请选择分类" clearable
                        style="width: 150px; margin-left: 10px;" @change="fetchData">
                        <el-option label="全部分类" :value="null"></el-option>
                        <el-option v-for="category in categoryOptions" :key="category.id" :label="category.name"
                            :value="category.id" />
                    </el-select>

                    <el-input v-model="searchKeyword" placeholder="搜索商品名称" style="width: 200px; margin-left: 10px;"
                        clearable @keyup.enter="fetchData">
                        <template #append>
                            <el-button icon="el-icon-search" @click="fetchData"></el-button>
                        </template>
                    </el-input>
                </div>
            </div>

            <el-table :data="tableData" style="width: 100%" border stripe v-loading="loading">
                <el-table-column prop="id" label="ID" width="80" align="center" />
                <el-table-column prop="name" label="商品名称" min-width="180" />
                <el-table-column label="商品图片" width="120" align="center">
                    <template #default="scope">
                        <el-image v-if="scope.row.image_url && scope.row.image_url.length > 0" 
                            :src="getImageUrl(JSON.parse(scope.row.image_url)[0])" 
                            class="goods-image"
                            :preview-src-list="JSON.parse(scope.row.image_url).map(url => getImageUrl(url))" 
                            fit="cover" hide-on-click-modal>
                            <template #error>
                                <div class="image-slot">
                                    <i class="el-icon-picture-outline"></i>
                                </div>
                            </template>
                        </el-image>
                        <div v-else class="no-image">
                            <i class="el-icon-picture"></i>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="selling_price" label="售价" width="100" align="center">
                    <template #default="scope">¥{{ scope.row.selling_price }}</template>
                </el-table-column>
                <el-table-column prop="disc_price" label="折扣价" width="100" align="center">
                    <template #default="scope">
                        <span v-if="scope.row.disc_price && scope.row.disc_price > 0">¥{{ scope.row.disc_price }}</span>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column prop="stock_num" label="库存" width="100" align="center" />
                <el-table-column label="分类" min-width="120">
                    <template #default="scope">
                        {{ categoryNameMap[scope.row.category_id] || '未知分类' }}
                    </template>
                </el-table-column>
                <el-table-column label="所属商家" min-width="150">
                    <template #default="scope">
                        {{ shopNameMap[scope.row.shop_id] || '未知商家' }}
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="100" align="center">
                    <template #default="scope">
                        <el-tag :type="getStatusType(scope.row.sale_status)">
                            {{ getStatusText(scope.row.sale_status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right" align="center">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="editGoods(scope.row)" plain round>编辑</el-button>
                        <el-button size="small" type="danger" @click="deleteGoods(scope.row)" plain round>删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px" :before-close="handleDialogClose">
            <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px" label-position="right">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="商品名称:" prop="name">
                            <el-input v-model="formData.name" placeholder="请输入商品名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="所属商家:" prop="shop_id">
                            <el-select v-model="formData.shop_id" placeholder="请选择所属商家" style="width: 100%"
                                @change="onShopChange">
                                <el-option v-for="shop in shopOptions" :key="shop.id" :label="shop.shop_name"
                                    :value="shop.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="商品分类:" prop="category_id">
                            <el-select v-model="formData.category_id" placeholder="请选择商品分类" style="width: 100%">
                                <el-option v-for="category in filteredCategoryOptions" :key="category.id"
                                    :label="category.name" :value="category.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="销售状态:" prop="sale_status">
                            <el-select v-model="formData.sale_status" placeholder="请选择销售状态" style="width: 100%">
                                <el-option label="上架" value="1"></el-option>
                                <el-option label="下架" value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="售价:" prop="selling_price">
                            <el-input v-model.number="formData.selling_price" placeholder="请输入售价">
                                <template #prepend>¥</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="折扣价:" prop="disc_price">
                            <el-input v-model.number="formData.disc_price" placeholder="请输入折扣价">
                                <template #prepend>¥</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="库存:" prop="stock_num">
                            <el-input v-model.number="formData.stock_num" placeholder="请输入库存数量" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="商品描述:">
                    <el-input v-model="formData.goods_desc" type="textarea" placeholder="请输入商品描述" :rows="3" />
                </el-form-item>

                <el-form-item label="商品图片:">
                    <el-upload
                        class="image-uploader"
                        action="http://localhost:8889/api/upload/goods"
                        method="post"
                        :file-list="fileList"
                        list-type="picture-card"
                        :on-success="handleImageSuccess"
                        :on-remove="handleImageRemove"
                        :before-upload="beforeImageUpload"
                        name="file"
                        multiple>
                        <el-icon><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDialogClose">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'

const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const searchKeyword = ref('')
const formRef = ref(null)
const isAddMode = ref(true)
const filterShopId = ref(null)
const filterCategoryId = ref(null)

// 文件列表
const fileList = ref([])

const baseUrl = 'http://localhost:8889' // 后端服务地址

// 商家选项
const shopOptions = ref([])

// 分类选项
const categoryOptions = ref([])

// 分类名称映射
const categoryNameMap = ref({})

// 商家名称映射
const shopNameMap = ref({})

// 根据选择的商家过滤分类选项
const filteredCategoryOptions = computed(() => {
    if (!formData.shop_id) return []

    // 返回平台通用分类(shop_id=0)和当前商家的分类
    return categoryOptions.value.filter(category =>
        category.shop_id === 0 || category.shop_id === formData.shop_id
    )
})

const formData = reactive({
    id: '',
    name: '',
    image_url: [], // 修改为数组
    selling_price: '',
    stock_num: '',
    disc_price: '',
    goods_desc: '',
    sale_status: '1',
    category_id: '',
    shop_id: ''
})

const formRules = {
    name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' }
    ],
    shop_id: [
        { required: true, message: '请选择所属商家', trigger: 'change' }
    ],
    category_id: [
        { required: true, message: '请选择商品分类', trigger: 'change' }
    ],
    selling_price: [
        { required: true, message: '请输入售价', trigger: 'blur' }
    ],
    stock_num: [
        { required: true, message: '请输入库存数量', trigger: 'blur' }
    ],
    sale_status: [
        { required: true, message: '请选择销售状态', trigger: 'change' }
    ]
}

const dialogTitle = computed(() => {
    return isAddMode.value ? '新增商品' : '编辑商品'
})

// 获取图片完整URL
const getImageUrl = (url) => {
    if (!url) return ''
    if (url.startsWith('http')) return url
    return `${baseUrl}${url}`
}

// 获取商家列表
const fetchShopOptions = async () => {
    try {
        const response = await axios.get(`${baseUrl}/api/admin/business/list`, {
            params: {
                page: 1,
                pageSize: 1000 // 获取所有商家
            }
        })

        if (response.data.code === 200) {
            shopOptions.value = response.data.data

            // 构建商家名称映射
            const map = {}
            response.data.data.forEach(shop => {
                map[shop.id] = shop.shop_name
            })
            shopNameMap.value = map
        } else {
            ElMessage.error(response.data.message || '获取商家列表失败')
        }
    } catch (error) {
        ElMessage.error('获取商家列表失败: ' + error.message)
    }
}

// 获取分类列表
const fetchCategoryOptions = async () => {
    try {
        const response = await axios.get(`${baseUrl}/api/admin/category/list`, {
            params: {
                page: 1,
                pageSize: 1000 // 获取所有分类
            }
        })

        if (response.data.code === 200) {
            categoryOptions.value = response.data.data

            // 构建分类名称映射
            const map = {}
            response.data.data.forEach(category => {
                map[category.id] = category.name
            })
            categoryNameMap.value = map
        } else {
            ElMessage.error(response.data.message || '获取分类列表失败')
        }
    } catch (error) {
        ElMessage.error('获取分类列表失败: ' + error.message)
    }
}

// 当商家改变时，清空分类选择
const onShopChange = () => {
    formData.category_id = ''
}

const getStatusText = (status) => {
    return status === '1' ? '上架' : '下架'
}

const getStatusType = (status) => {
    return status === '1' ? 'success' : 'info'
}

const fetchData = async () => {
    loading.value = true
    try {
        const response = await axios.get(`${baseUrl}/api/admin/goods/list`, {
            params: {
                page: currentPage.value,
                pageSize: pageSize.value,
                name: searchKeyword.value,
                ...(filterShopId.value !== null && { shop_id: filterShopId.value }),
                ...(filterCategoryId.value !== null && { category_id: filterCategoryId.value })
            }
        })

        if (response.data.code === 200) {
            tableData.value = response.data.data
            total.value = response.data.pagination.total
        } else {
            ElMessage.error(response.data.message || '获取商品列表失败')
        }
    } catch (error) {
        ElMessage.error('获取商品列表失败: ' + error.message)
    } finally {
        loading.value = false
    }
}

const addGoods = () => {
    isAddMode.value = true
    resetForm()
    dialogVisible.value = true
}

const editGoods = (row) => {
    isAddMode.value = false
    // 重置文件列表
    fileList.value = []
    
    // 处理图片URL数组
    let imageUrls = []
    if (row.image_url) {
        try {
            imageUrls = JSON.parse(row.image_url)
        } catch (e) {
            // 如果解析失败，可能是一个字符串
            imageUrls = [row.image_url]
        }
    }
    
    Object.assign(formData, {
        ...row,
        image_url: imageUrls
    })
    
    // 设置文件列表用于显示
    fileList.value = imageUrls.map((url, index) => ({
        name: `image_${index}.png`,
        url: getImageUrl(url)
    }))
    
    dialogVisible.value = true
}

const deleteGoods = (row) => {
    ElMessageBox.confirm(
        `确定要删除商品"${row.name}"吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            const response = await axios.delete(`${baseUrl}/api/admin/goods/${row.id}`)
            if (response.data.code === 200) {
                ElMessage.success('删除成功')
                fetchData()
            } else {
                ElMessage.error(response.data.message || '删除失败')
            }
        } catch (error) {
            ElMessage.error('删除失败: ' + error.message)
        }
    }).catch(() => {
        // 用户取消删除
    })
}

const resetForm = () => {
    Object.assign(formData, {
        id: '',
        name: '',
        image_url: [],
        selling_price: '',
        stock_num: '',
        disc_price: '',
        goods_desc: '',
        sale_status: '1',
        category_id: '',
        shop_id: ''
    })
    fileList.value = []
    if (formRef.value) {
        formRef.value.resetFields()
    }
}

const handleDialogClose = (done) => {
    dialogVisible.value = false
    resetForm()
}

// 图片上传成功处理
const handleImageSuccess = (response, uploadFile, uploadFiles) => {
    if (response.code === 200) {
        // 更新文件列表
        fileList.value = uploadFiles.map(file => {
            if (file.response && file.response.code === 200) {
                return {
                    name: file.name,
                    url: getImageUrl(file.response.data.goods_img_url)
                }
            } else {
                return file
            }
        })
        
        ElMessage.success('图片上传成功')
    } else {
        ElMessage.error(response.message || '图片上传失败')
    }
}

// 图片移除处理
const handleImageRemove = (uploadFile, uploadFiles) => {
    fileList.value = uploadFiles
}

const beforeImageUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('商品图片只能是 JPG 或 PNG 格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('商品图片大小不能超过 5MB!')
        return false
    }
    return true
}

const submitForm = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true
            try {
                // 获取所有上传成功的图片URL
                const imageUrls = fileList.value
                    .filter(file => file.response && file.response.code === 200)
                    .map(file => file.response.data.goods_img_url)
                
                // 如果没有新上传的图片，使用原始图片URL
                const finalImageUrls = imageUrls.length > 0 
                    ? imageUrls 
                    : formData.image_url

                const requestData = {
                    name: formData.name,
                    image_url: JSON.stringify(finalImageUrls), // 转换为JSON字符串
                    selling_price: formData.selling_price,
                    stock_num: formData.stock_num,
                    disc_price: formData.disc_price,
                    goods_desc: formData.goods_desc,
                    sale_status: formData.sale_status,
                    category_id: formData.category_id,
                    shop_id: formData.shop_id
                }

                let response
                if (isAddMode.value) {
                    // 新增商品
                    response = await axios.post(`${baseUrl}/api/admin/goods/addGoods`, requestData)
                } else {
                    // 编辑商品
                    response = await axios.put(`${baseUrl}/api/admin/goods/${formData.id}`, requestData)
                }

                if (response.data.code === 200) {
                    ElMessage.success(isAddMode.value ? '新增商品成功' : '编辑商品成功')
                    dialogVisible.value = false
                    fetchData()
                } else {
                    ElMessage.error(response.data.message || (isAddMode.value ? '新增商品失败' : '编辑商品失败'))
                }
            } catch (error) {
                ElMessage.error((isAddMode.value ? '新增商品失败' : '编辑商品失败') + ': ' + error.message)
            } finally {
                submitLoading.value = false
            }
        }
    })
}

const handleSizeChange = (val) => {
    pageSize.value = val
    fetchData()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchData()
}

onMounted(() => {
    fetchShopOptions()
    fetchCategoryOptions()
    fetchData()
})
</script>

<style scoped>
.goods-management-container {
    min-height: calc(100vh - 80px);
}

.header-card {
    background: #409eff;
    color: white;
    padding: 20px 30px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-card h2 {
    margin: 0 0 10px 0;
    font-size: 24px;
    font-weight: 500;
}

.header-card p {
    margin: 0;
    opacity: 0.9;
    font-size: 14px;
}

.table-card {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.toolbar {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding: 15px 0;
}

.goods-image {
    width: 60px;
    height: 60px;
    border-radius: 6px;
}

.image-slot {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 60px;
    height: 60px;
    color: #c0c4cc;
}

.image-slot i {
    font-size: 20px;
}

.no-image {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60px;
    height: 60px;
    color: #c0c4cc;
    border: 1px dashed #dcdfe6;
    border-radius: 6px;
}

.no-image i {
    font-size: 20px;
}

.image-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.image-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.image-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    text-align: center;
}
</style>